package org.dromara.admin.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.admin.domain.Order;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.*;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页服务实现类
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HomeServiceImpl implements IHomeService {

    private final IEmployeeService employeeService;
    private final ICustomerService customerService;
    private final ISupplierService supplierService;
    private final IProductService productService;
    private final IOrderService orderService;

    /**
     * 首页面板数据统计
     *
     * @param employeeId 登录员工ID
     * @return 统计数据(今日 、 本月订单数量以及销售额统计 + 客户总数 + 产品总数 + 最近10条订单)
     */
    @Override
    public Map<String, Object> getCompanySummary(Long employeeId) {
        // 获取登录用户的主体公司id
        EmployeeVo employeeVo = employeeService.queryById(employeeId);
        Long companyId = employeeVo.getCompanyId();

        Map<String, Object> map = new HashMap<>();
        // ========= 时间定义 =========
        DateTime todayStart = DateUtil.beginOfDay(DateUtil.date()); // 今日开始
        DateTime todayEnd = DateUtil.endOfDay(DateUtil.date()); // 今日结束
        DateTime monthStart = DateUtil.beginOfMonth(DateUtil.date()); // 本月开始
        DateTime monthEnd = DateUtil.endOfMonth(DateUtil.date()); // 本月结束

        // ========= 今日/本月订单数量以及销售额统计 =========
        Map<String, Object> todayStats = orderService.getOrderStats(companyId, todayStart, todayEnd);
        Map<String, Object> monthStats = orderService.getOrderStats(companyId, monthStart, monthEnd);
        map.put("todayOrderCount", todayStats.get("orderCount"));
        map.put("todaySalesAmount", todayStats.get("salesAmount"));
        map.put("monthOrderCount", monthStats.get("orderCount"));
        map.put("monthSalesAmount", monthStats.get("salesAmount"));

        // ========= 客户总数 =========
        Long customerTotal = customerService.queryCustomerTotalByCompanyId(companyId);
        map.put("customerTotal", customerTotal);

        // ========= 供应商总数 =========
        Long supplierTotal = supplierService.querySupplierTotalByCompanyId(companyId);
        map.put("supplierTotal", supplierTotal);

        // ========= 产品总数 =========
        Long productTotal = productService.queryProductTotalByCompanyId(companyId);
        map.put("productTotal", productTotal);

        // ========= 获取最近10条订单 =========
        List<Order> recent10OrderList = orderService.queryRecent10OrderListByCompanyId(companyId);
        map.put("recentOrders", recent10OrderList);
        return map;
    }
}
